package processing;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import model.Keyterms;
import model.Result;
import model.ResultSetWeb;
import model.Terms;
import model.YSearchResponse;

import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;

public class XMLExtractor {
  
  public static YSearchResponse extractFromString(String xml) {
    SAXBuilder sb = new SAXBuilder(true);
    sb.setValidation(false);
    org.jdom.Document d = null;

    try {
      d = sb.build(new StringReader(xml));
      
    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    
    return extract(d);
  }
  
  public static YSearchResponse extractFromFile(String filename) {
    SAXBuilder sb = new SAXBuilder();
    sb.setValidation(false);
    
    org.jdom.Document d = null;
    
    try {
      d = sb.build(new File(filename));
    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return extract(d);
  }
    
  private static YSearchResponse extract(org.jdom.Document d) {
    YSearchResponse ysr = null;

    Element root = d.getRootElement();
    Namespace ns = root.getNamespace();

    // <ysearchresponse>
    ysr = new YSearchResponse();
    ysr.setResponsecode( root.getAttribute("responsecode").getValue());
    
    Element tag_resultsetweb = root.getChild("resultset_web", ns);
     
    // <resultset_web>
    ResultSetWeb rsw = new ResultSetWeb();
    rsw.setCount(tag_resultsetweb.getAttribute("count").getValue());
    rsw.setStart(tag_resultsetweb.getAttribute("start").getValue());
    rsw.setTotalhits(tag_resultsetweb.getAttribute("totalhits").getValue());
    rsw.setDeephits(tag_resultsetweb.getAttribute("deephits").getValue());

    ysr.setResultSet(rsw);

    int recordcount = 0;

    // para cada <RESULT>
    for (Element e : (List<Element>)tag_resultsetweb.getChildren("result", ns) ) {
      Result r = new Result();
      r.setAbstract(e.getChildText("abstract", ns));
      r.setTitle(e.getChildText("title", ns));
      r.setUrl(e.getChildText("url", ns));

      Keyterms keyterms = new Keyterms();
      Terms terms = new Terms();
      List<Element> tag_terms = e.getChild("keyterms", ns).getChild("terms", ns).getChildren("term", ns);

      for (Element l : tag_terms) {
        terms.addTerm(l.getText());
      }
      keyterms.setTerms(terms);
      r.setKeyterms(keyterms);

      rsw.addResult(r);

      recordcount++;
    }
    
    return ysr;
  }
  
}
